package com.qf.service.impl;

import com.qf.dao.CartDao;
import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailDao;
import com.qf.dao.impl.CartDaoImpl;
import com.qf.dao.impl.OrderDaoImpl;
import com.qf.dao.impl.OrderDetailDaoImpl;
import com.qf.entity.Cart;
import com.qf.entity.Order;
import com.qf.entity.OrderDetail;
import com.qf.service.OrderService;
import com.qf.util.DataSourceUtils;

import java.util.List;

/**
 * @author wgy
 * @version V1.0
 * @project java2402_xiaomi
 * @package com.qf.service.impl
 * @company 千锋教育
 * @date 2024/6/13 14:15
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao=new OrderDaoImpl();
    @Override
    public void add(Order order, List<Cart> cartList) {

        try {
            DataSourceUtils.begin();
            //1 向订单表中添加数据
            orderDao.insert(order);
            //int i=1/0;
            //2 向订单详情表
            OrderDetailDao orderDetailDao=new OrderDetailDaoImpl();
            for (Cart cart : cartList) {
                OrderDetail orderDetail=new OrderDetail(null,order.getId(),cart.getPid(),cart.getNum(),cart.getMoney(),null);
                orderDetailDao.insert(orderDetail);
            }
            //3 删除购物车信息
            CartDao cartDao=new CartDaoImpl();
            cartDao.deleteByUid(order.getUid());
            DataSourceUtils.commit();
        } catch (Exception e) {
            DataSourceUtils.rollback();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateState(String oid, String status) {
        orderDao.updateState(oid,status);
    }

    @Override
    public List<Order> findByUid(int uid) {
        return orderDao.selectByUid(uid);
    }

    @Override
    public Order findByOid(String oid) {
        return orderDao.selectByOid(oid);
    }

    @Override
    public List<OrderDetail> findOrderDetail(String oid) {
        return orderDao.selectOrderDetail(oid);
    }
}
